package com.linser.gistools.common.property;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author: linser
 * @Desc: 加密属性工厂类
 * @create: 2024-02-01 10:26
 **/
public class EncryptedPropertiesFactory {
    /** The singleton instance. */
    private static EncryptedPropertiesInterface instance = null;

    /** The encrypted properties class name. */
    @SuppressWarnings("unused")
    private static String encryptedPropertiesClassName = null;

    /**
     * Override class name.
     *
     * @param className the class name
     */
    public static void overrideClassName(String className) {
        encryptedPropertiesClassName = className;
    }

    /** Reset singleton. */
    public static void reset() {
        instance = null;
    }

    /**
     * Gets the singleton instance of EncryptedPropertiesFactory.
     *
     * @return singleton instance of EncryptedPropertiesFactory
     */
    public static synchronized EncryptedPropertiesInterface getInstance() {
        if (instance == null) {
            String password = generatePassword();

            try {
                instance = new EncryptedPropertiesBase64();

                instance.initialise(password);
            } catch (Exception e) {
                //TODO
                //ConsoleManager.getInstance().exception(EncryptedPropertiesFactory.class, e);
            }
        }

        return instance;
    }

    /**
     * Generate password.
     *
     * @return the string
     */
    private static String generatePassword() {
        StringBuilder sb = new StringBuilder();

        sb.append(getUniqueIdentifier());

        sb.append(System.getProperty("user.name"));

        return sb.toString();
    }

    /**
     * Gets a unique identifier using the machine name.
     *
     * @return the unique identifier
     */
    private static String getUniqueIdentifier() {
        String hostname = "Unknown";

        try {
            InetAddress addr = InetAddress.getLocalHost();
            hostname = addr.getHostName();
        } catch (UnknownHostException ex) {
            //TODO
            //ConsoleManager.getInstance().error(EncryptedPropertiesFactory.class, "Hostname can not be resolved");
        }

        return hostname;
    }

    /**
     * Decrypt a string.
     *
     * @param str the str
     * @return the string
     */
    public synchronized String decrypt(String str) {
        return instance.decrypt(str);
    }

    /**
     * Encrypt a string.
     *
     * @param str the str
     * @return the string
     */
    public synchronized String encrypt(String str) {
        return instance.encrypt(str);
    }
}
